import axios from 'axios'
import { getNewToken } from '@/api/api'
import { useTokenStore } from '@/stores'
import CryptoJS from 'crypto-js'
const TokenStore = useTokenStore()
axios.defaults.baseURL = 'https://4003d434.r11.vip.cpolar.cn'
const day = new Date()
const axiosInstance = axios.create({
 timeout: 5 * 1000, // 请求超时时间（5秒）
 retry: 0, // 禁用全局重试（使用基于拦截器的重试）
 retryDelay: 1000 // 全局请求间隔（由于禁用了全局重试，此项未使用）
})
//获取随机字符串
export const generateRandomString = () => {
 const characters =
  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
 const charactersLength = characters.length
 const randomLength = Math.floor(Math.random() * 4) + 5 // 生成一个5到8之间的随机整数
 let result = ''

 for (let i = 0; i < randomLength; i++) {
  result += characters.charAt(Math.floor(Math.random() * charactersLength))
 }

 return result
}
//加密
const encrypt = (data) => {
 const time = JSON.stringify(day.getTime())
 const key = generateRandomString()
 const encrypted = CryptoJS.AES.encrypt(JSON.stringify(data), time).toString()
 let newdata = {
  time: time,
  key,
  data: encrypted
 }
 return newdata
}

//刷新token
const rToken = () => {
 return new Promise((resolve) => {
  getNewToken().then((res) => {
   TokenStore.setAccessToken(res.data.access_token)
   TokenStore.setRefreshToken(res.data.refresh_token)
   resolve()
  })
 })
}

export const request = (options) => {
 return new Promise((resolve, reject) => {
  axiosInstance(options)
   .then((response) => resolve(response.data))
   .catch((error) => reject(error))
 })
}

// 添加响应拦截器
axiosInstance.interceptors.response.use(
 (response) => {
  // 如果响应成功，直接返回响应数据
  return response
 },
 (error) => {
  const { response, config } = error
  if (response && response.status === 400) {
   return rToken().then(() => {
    const token = JSON.parse(localStorage.getItem('token')).accessToken
    // 更新请求的 token
    config.headers['token'] = token
    // 重新发送请求
    return axiosInstance(config)
   })
  }
  // 对其他错误不做处理，直接抛出错误
  return Promise.reject(error)
 }
)

//添加请求拦截器
axiosInstance.interceptors.request.use(
 (config) => {
  // console.log(config)
  // 在发送请求之前对data进行加密
  if (config.data) {
   config.data = encrypt(config.data)
  } else if (config.params) {
   config.params = encrypt(config.params)
  }
  return config
 },
 (error) => {
  // 对请求错误做些什么
  console.error('Request error:', error)
  return Promise.reject(error)
 }
)
